<?php
namespace backend\controllers;
use Yii;
use yii\db\Query;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\ForbiddenHttpException;
use yii\grid\GridView;
use yii\helpers\Html;
use yii\base\Object;
use yii\base\Response;
use backend\models\GrpCity;
use backend\models\SysItem;
use yii\widgets\ActiveForm;
use backend\models\OperatorRelation;
use backend\models\OperatorRelationSearch;
use yii\data\ActiveDataProvider;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
use yii\data\ArrayDataProvider;
use common\models\UserInfo;
/**
 * 运营商控制器
 * @author suiyue
 *
 */
class OperatorRelationController extends BaseController
{
	/**
	 * (non-PHPdoc)行为
	 * @see \yii\base\Component::behaviors()
	 */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * (non-PHPdoc)前置函数
     * @see \yii\web\Controller::beforeAction()
     */
    public function beforeAction($action)
    {
    	$action = Yii::$app->controller->action->id;
    	$controller = Yii::$app->controller->id;
    	$action_list = array(
    			'index',
    			'update',
    			'view',
    			'create',
    	        'city',
    	       'getcitylist',
    	       'delete',
    	       'backoperator',
    	       'deloperator'
    	);
    	 $access=$this->checkAccess($action_list,$action);//判断操作的action是否在actionlist里面
    	 $this->beforeOp('brand', $access);//身份识别 权限验证  action验证
    	 return true;
    }
    /**
     * 删除运营商
     */
    public function actionDeloperator(){
        $id=Yii::$app->request->post('id');
        $model=$this->findModel($id);
        $model->city1=$model->city_id;
        $model->useing=0;
        $result=$model->save();
        echo $result;exit();
    }
    /**
     * 恢复运营商
     */
    public function actionBackoperator(){
        $id=Yii::$app->request->post('id');
        $useing=Yii::$app->request->post('useing');
        $citylist=Yii::$app->request->post('citylist');
        $model=$this->findModel($id);
        $model->city1=$model->city_id;
        $old_city_list=$citylist;
        $old_use=intval($model->useing);
        if($old_use!=intval($useing)){
            if(intval($useing)==1){
                $ifExit=false;
                foreach($old_city_list as $citylistId){
                    $sql="select uid from prf_operator_relation where city_list like '%$citylistId%' and useing=1";
                    $operatorInfo=OperatorRelation::findBySql($sql)->asArray()->all();
                    if(count($operatorInfo)>0){
                        $ifExit=true;
                        break;
                    }
                }
                if($ifExit){
                    echo 2;exit();
                } 
            }    
        } 
        echo 1;exit();
    }
	/**
	 * 运营商列表
	 */
    public function actionIndex()
    {
        $operatorRelation=new OperatorRelation();
    	$searchModel = new OperatorRelationSearch();
    	$dataProvider=$searchModel->search(Yii::$app->request->queryParams);
    	return $this->render('index', [
    			'searchModel' => $searchModel,
    			'dataProvider' => $dataProvider,
    	]);
    }
    /**
     * 创建运营商
     */
    public function actionCreate(){
    	//$this->layout = 'main_small';
    	$model = new OperatorRelation();
    	if ($model->load(Yii::$app->request->post())&&$model->validate()) {
    		//ajax验证
    		if(Yii::$app->request->isAjax){
    			Yii::$app->response->format=Response::FORMAT_JSON;
    			return ActiveForm::validate($model);
    		}
    		$post=Yii::$app->request->post();
    		//判断uid是id还是手机号  
    		$uid=intval($post['OperatorRelation']['uid']);
    		$parent=intval($post['OperatorRelation']['parent']);
    		if($uid>0){
    		    $model->uid=$model->getuid($uid,"create"); 
    		}
    		if($parent>0){
    		    $model->parent=$model->getuid($parent,"create");
    		}
    		if(intval($model->uid)>0){
    		    //获取city_id
    		    $operatorRelation=$post['OperatorRelation'];
    		    $model->city_id=$model->getCityIdByPost($operatorRelation);
    		    if($operatorRelation['city_list']!="" ){ 
    		        $model->city_list=implode(",", $post['OperatorRelation']['city_list']);
    		    }else{
    		        //再验证所管辖区域是否可以为空
    		        $city1=$operatorRelation['city1'];
    		        $city2=$operatorRelation['city2'];
    		        if(key_exists('city3', $operatorRelation)){
    		            $city3=$operatorRelation['city3'];
    		        }else{
    		            $city3=0;
    		        }
    		        $checkIfexits=$model->checkChoose($city1, $city2, $city3);
    		        if($checkIfexits==1){
    		            //不可为空
    		            echo '<script type="text/javascript">alert("当前某区域已被选择，不可为空默认全选，请选择!");window.history.go(-1);exit();</script>';
    		            $model= new OperatorRelation();
    		            $model->city_list=$model->getAllProvince();
    		            return $this->render('create', [
    		                'model' => $model,
    		            ]);
    		        }else{
    		            $model->city_list=$model->getcity_listByPost($operatorRelation);
    		        }
    		       
    		    }
    		    $model->memo=$post['OperatorRelation']['memo'];
    		    $model->useing=1;
    		    //查询是否重复城市或者省份，如果重复，则合并数据
    		    $OperatorInfo = OperatorRelation::find()->where('useing=1 and city_id=:cityid and uid=:uid',array(":cityid"=>$model->city_id,":uid"=>$model->uid))->one();
    		    if(count($OperatorInfo)>0){
    		        //合并数据
    		        $oldListStr=$OperatorInfo['city_list'];
    		        $newListStr=$model->city_list;
    		        $ListStrNow=$oldListStr.",".$newListStr;
    		        $OperatorInfo['city_list']=$ListStrNow;
    		        $OperatorInfo['city1']=330100;//完成验证
    		        $OperatorInfo->save();
    		        $this->redirect(['index']);
    		    }else{
    		        $model->save();
    		        $this->redirect(['index']);
    		    }
    		}else{
    		    echo '<script type="text/javascript">alert("抱歉，运营商填入错误,请重新填入!");window.history.go(-1);exit();</script>';
    		    $model= new OperatorRelation();
    		    $model->city_list=$model->getAllProvince();
    		    return $this->render('create', [
    		        'model' => $model,
    		    ]);
    		}
    	}else{
    	    $model->city_list=$model->getAllProvince();
    		return $this->render('create', [
    				'model' => $model,
    		]);
    	}
    }
    /**
     * 获取城市
     */
    public function actionCity(){
        $q=Yii::$app->request->post('q');
        $id=Yii::$app->request->post('id');
        $value="";
 /*        $id=330000;
        $q="city"; */
        $model=new OperatorRelation();
            if ($q== 'city') {//获取城市
                 $value=$model->getCitylistByProvince($id);
            } elseif ($q == 'area2') {//获取直辖市的下级
                $value = GrpCity::area2($id);
                $count=count($value);
                for($i=0;$i<$count;$i++){
                    $cityid=$value[$i]['id'];
                    $sql="select uid from prf_operator_relation where city_list like '%$cityid%'   and useing=1";
                    $operator=OperatorRelation::findBySql($sql)->asArray()->all();
                    if(count($operator)>0){//如果运营商表存在这个城市，则去除
                        unset($value[$i]);
                    }
                }
            } elseif ($q == 'area') {//获取区县
                $value = GrpCity::find()->where(['like','id',intval($id/100).'%',false])->andWhere(['<>','id',$id])->asArray()->all();
                $count=count($value);
                for($i=0;$i<$count;$i++){
                    $cityid=$value[$i]['id'];
                    $sql="select uid from prf_operator_relation where city_list like '%$cityid%'  and  useing=1";
                    $operator=OperatorRelation::findBySql($sql)->asArray()->all();
                    if(count($operator)>0){//如果运营商表存在这个城市，则去除
                        unset($value[$i]);
                    }
                }
            }elseif($q=='citylist'){//根据省份获取城市
                
                $value=$model->getGxCitylistByProvince($id);
            }
            if(count($value)>0){
                echo json_encode($value, JSON_UNESCAPED_UNICODE);
            }else{
                echo "{}";
            }
            exit();
       }
    /**
     * 根据id获取管辖区域
     */
    public function actionGetcitylist(){
        $uid=Yii::$app->request->post('uid');
        if(intval($uid)>0){
            $sql="select city_list from prf_operator_relation where uid=:id";
            $operatorRelation=OperatorRelation::findBySql($sql,array(":id"=>$uid))->asArray()->one();
            $city_result=array();
            $city_listArray=explode(",",$operatorRelation['city_list']);
            for($i=0;$i<count($city_listArray);$i++){
                $city_Info=GrpCity::findBysql("select id,name from grp_city where id=:id ",array(":id"=>$city_listArray[$i]))->One(); 
                $city_result[]=array("id"=>$city_Info['id'],"name"=>$city_Info['name']);
            }
            echo json_encode($city_result,true);exit();
        }else{
            echo "";exit();
        }
    }
    /**
     * 修改
     */
    public function actionUpdate ($id){
    	//$this->layout = 'main_small';
        $model=$this->findModel($id);
        $old_use=intval($model->useing);
        $old_cityid=intval($model->city_id);
        $old_citylist=$model->city_list;
        $operator=new OperatorRelation();
        if ($model->load(Yii::$app->request->post())&&$model->validate()) {
            //ajax验证
            if(Yii::$app->request->isAjax){
                Yii::$app->response->format=Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            }
            $post=Yii::$app->request->post();
            $operatorRelation=$post['OperatorRelation'];
            if($old_use!=intval($operatorRelation['useing'])){
                if(intval($operatorRelation['useing'])==1){
                    $ifExit=false;
                    //$old_city_list=explode(",", $old_citylist);
                    $old_city_list=$model->city_list;
                    foreach($old_city_list as $citylistId){
                        $sql="select uid from prf_operator_relation where city_list like '%$citylistId%' and useing=1";
                        $operatorInfo=OperatorRelation::findBySql($sql)->asArray()->all();
                        if(count($operatorInfo)>0){
                            $ifExit=true;
                            break;
                        }
                    }
                    if($ifExit){
                        echo '<script type="text/javascript">alert("抱歉，管辖区域已被其他运营商管理，不可恢复!");window.history.go(-1);exit();</script>';
                        return $this->redirect(['update','id'=>$model['id']]);
                    }else{
                        $model->useing=1;
                    }
                    //验证管辖区域是否已被占领，如果被占领，不可以恢复
                }
            }
            //判断uid是id还是手机号
            $parent=intval($post['OperatorRelation']['parent']);
            if($parent>0){
                $model->parent=$operator->getuid($parent,"update");
            }
            if($parent>0){
                $newparent=intval($operator->getuid($parent,"update"));
                if($newparent==0){
                    echo '<script type="text/javascript">alert("抱歉，上级运营商填入错误,请重新填入!");</script>';
                    return $this->redirect(['update','id'=>$model['id']]);
                }
            }
            //if(intval($model->uid)>0){
                //获取city_id
                $model->city_id=$operator->getCityIdByPost($operatorRelation);
                if($operatorRelation['city_list']!="" ){
                    $model->city_list=implode(",", $post['OperatorRelation']['city_list']);
                }else{
                    //管辖城市没做修改  所属城市也没修改  进行删除数据
                    if($old_cityid==intval($model->city_id)){
                        //没有修改城市   直接删除数据
                        $model->delete();
                        return $this->redirect(['index']);exit();
                    }else{
                        $city1=$operatorRelation['city1'];
                        $city2=$operatorRelation['city2'];
                        if(key_exists('city3', $operatorRelation)){
                            $city3=$operatorRelation['city3'];
                        }else{
                            $city3=0;
                        }
                        $checkIfexits=$operator->checkChoose($city1, $city2, $city3);
                        if($checkIfexits==1){
                            echo '<script type="text/javascript">alert("当前某区域已被选择，不可为空默认全选，请选择!");</script>';
                           // $model= new OperatorRelation();
                            $model->city_list=$operator->getAllProvince();
                            return $this->redirect(['update','id'=>$model['id']]);
                           /*  return $this->render('create', [
                                'model' => $model,
                            ]); */
                        }else{
                            $model->city_list=$operator->getcity_listByPost($operatorRelation);
                        } 
                    }
                    //如果管辖区域为空，则删除该运营商
                    //再验证所管辖区域是否可以为空
                    
                 /*   */
                }
                //判断有没有重复 ，如果重复了，就合并数据
                if(intval($model->useing)==1){
                    $OperatorInfo = OperatorRelation::find()->where('useing=1 and city_id=:cityid and uid=:uid and id!=:id',array(":cityid"=>$model->city_id,":uid"=>$model->uid,":id"=>$model->id))->one();
                    if(count($OperatorInfo)>0){
                        //合并数据
                        $oldListStr=$OperatorInfo['city_list'];
                        $newListStr=$model->city_list;
                        $ListStrNow=$oldListStr.",".$newListStr;
                        $OperatorInfo['city_list']=$ListStrNow;
                        $OperatorInfo['city1']=330100;//完成验证
                        $OperatorInfo->save();
                        //删除当前的运营商
                        $model->delete();
                        $this->redirect(['index']);
                    }else{
                        $model->memo=$post['OperatorRelation']['memo'];
                        $model->save();
                        return $this->redirect(['view', 'id' => $model->id]);
                    }
                }else{
                    $model->memo=$post['OperatorRelation']['memo'];
                    $model->save();
                    return $this->redirect(['view', 'id' => $model->id]);
                }
        //反填充页面        
        } else{
            //反填充省份
            $cityId= $model->city_id ;
            $str=substr($cityId,2);
            $firstStr=substr($cityId, 0,2);
            $provinceId=intval($firstStr."0000");
            if($str=="0000"){
                $model->city1List=$operator->getProvince($cityId);
               $value=$model->getCitylistByProvince($cityId);
                $model->city2=$operator->getFormartAllProvinceOnUpdate($value);
                $model->city3=[];
            }else{
                $str=substr($cityId, 4);
                $model->city1List=$model->getProvince($provinceId);
                if($str=="00"){
                    //计算城市    
                    $city2Info=GrpCity::findBySql('SELECT id,name  FROM `grp_city` WHERE id=:id',array(":id"=>$cityId))->asArray()->One();
                    $model->city2[$city2Info['id']]=$city2Info['name'];
                    $value=$operator->getCitylistByProvince($provinceId);
                    foreach($value as $v){
                        $model->city2[$v['id']]=$v['name'];
                    }
                    $model->city3=[];
                }else{//区县
                    $firstStr=substr($cityId, 0,4);
                    $cId=intval($firstStr."00");
                    $specilProvince=array('110000','120000','310000','500000');//直辖市
                    if(in_array($provinceId, $specilProvince)){
                        //直辖市
                        $model->city3=[];
                        $city2Info=GrpCity::findBySql('SELECT id,name  FROM `grp_city` WHERE id=:id',array(":id"=>$cityId))->asArray()->One();
                        $model->city2[$city2Info['id']]=$city2Info['name'];
                        //计算城市
                        $value=$model->getCitylistByProvince($provinceId);
                        foreach($value as $v){
                            $model->city2[$v['id']]=$v['name'];
                        }
                    }else{
                        $city2Info=GrpCity::findBySql('SELECT id,name  FROM `grp_city` WHERE id=:id',array(":id"=>$cId))->asArray()->One();
                        $model->city2[$city2Info['id']]=$city2Info['name'];
                        //计算城市
                        $value=$model->getCitylistByProvince($provinceId);
                        foreach($value as $v){
                            $model->city2[$v['id']]=$v['name'];
                        }
                        $city3Info=GrpCity::findBySql('SELECT id,name  FROM `grp_city` WHERE id=:id',array(":id"=>$cityId))->asArray()->One();
                        $model->city3[$city3Info['id']]=$city3Info['name'];
                        //计算区
                        $value=$model->getCountrylistByCity($cId);
                        foreach($value as $v){
                            $model->city3[$v['id']]=$v['name'];
                        }
                    }
                }
            }
            $citylistArray=explode(",",$model->city_list);
            $citylist=$operator->getCitylistOnUpdateByCityid(intval($model->city_id),$model->id,$citylistArray);
            $model->city_list=explode(",",$model->city_list);
            $model->city_list_old=$citylist;
            //判断是不是直辖市
            $iszhixia="false";
            $specilProvince=array('110000','120000','310000','500000');//直辖市
            if(in_array($provinceId,$specilProvince)){
                $iszhixia="true";
            }
            return $this->render('update', [
                'model' => $model,
                'iszhixia'=>$iszhixia
            ]);
        }
    }
   
   /**
    * 删除
    * @param   $id
    */
    public function actionDelete($id){
        $model=$this->findModel($id);
        $model->city1=$model->city_id;
        $model->useing=0;
        $model->save();
        return $this->redirect(['index']);
        
    }
    
   /**
     * 查看单条数据
     */
    public function actionView($id){
        $operator=new OperatorRelation();
    	$this->layout = 'main_small';
    	$model=$this->findModel($id);
    	if($model->parent!=0){
    	    $sql="select prf_operator_relation.*,u1.tel ,u2.tel parent,sys_user_designer.name username   from
        prf_operator_relation ,user_info u1,user_info u2,sys_user_designer 
        where u1.id=prf_operator_relation.uid and u2.id=prf_operator_relation.parent and sys_user_designer.uid=prf_operator_relation.uid
        and prf_operator_relation.id=:id ";
    	    $model = OperatorRelation::findBySql($sql,array(":id"=>$id))->asArray()->one();
    	}else{
    	    $sql="select prf_operator_relation.*,u1.tel,sys_user_designer.name username  from
        prf_operator_relation ,user_info u1 ,sys_user_designer 
        where u1.id=prf_operator_relation.uid    and sys_user_designer.uid=prf_operator_relation.uid
        and prf_operator_relation.id=:id ";
    	    $model = OperatorRelation::findBySql($sql,array(":id"=>$id))->asArray()->one();
    	}
    	
    	$city_id=$model['city_id'];
    	$model['city_id']=$operator->getCityName($city_id);
    	if(key_exists("city_list", $model)){
    	    $city_list_str=$model['city_list'];
    	    $model['city_list']=$operator->getCitylistStr($city_list_str);
        }else{
            $model=$this->findModel($id);
        }
    	return $this->render('view', [
    			'model' => $model
    	]);
    }
    /**
     * 点击添加或者修改  判断所管辖区域是否选择了  如果没选择，重新操作
     */
    /**
     * 查找单个
     * @param   $id
     * @throws NotFoundHttpException
     */
    protected function findModel($id)
    {
        if (($model = OperatorRelation::findOne($id)) !== null) {
            $model = OperatorRelation::find()->where('id='.$id)->one();
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
   
    
}
